package com.example.xinlijiankangsys.service;

import com.example.xinlijiankangsys.mapper.UserInfoMapper;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserInfoService {
    @Autowired
    private  UserInfoMapper userInfoMapper;

    @Autowired
    private UserService userService;
    /**
     * 获取用户基本信息（Map形式）
     */
    public Map<String, Object> getUserBasicInfo(String userId) {
        Map<String, Object> userMap = userInfoMapper.getUserBasicInfo(userId);
        System.out.println("基本信息: "+userMap);
        if (userMap == null || userMap.isEmpty()) {
            throw new RuntimeException("用户信息不存在");
        }
        // 处理默认头像
        userMap.putIfAbsent("avatar_path", "/static/avatars/default.png");

        return userMap;
    }

    /**
     * 获取用户信息（Map形式）
     * @param userId 用户ID
     * @return 标准化后的Map（处理空值和默认值）
     */
    public Map<String, Object> getUserInfoAsMap(String userId) {
        Map<String, Object> userMap = userInfoMapper.getUserAsMap(userId);
        if (userMap == null || userMap.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        // 处理默认值
        userMap.putIfAbsent("avatar_path", "/avatars/default.png");
//        userMap.computeIfAbsent("auth_name", k -> {
//            int auth = (int) userMap.get("auth");
//            return switch (auth) {
//                case 1 -> "学生";
//                case 2 -> "心理咨询师";
//                default -> "辅导员";
//            };
//        });

        return userMap;
    }


    /**
     * 获取匹配关键字的用户ID列表
     */
    public List<Map<String, Object>> searchUsers(String keyword) {
        // 1. 执行模糊查询

        List<Map<String, Object>> rawResults = userInfoMapper.searchUsers(
                keyword.replaceAll("[%_]", "\\\\$0") // 防SQL注入
        );

//        List<String> stringList;
        // 2. 转换为标准格式
        return rawResults.stream()
                .map(this::convertToStandardFormat)
                .collect(Collectors.toList());
    }

    private Map<String, Object> convertToStandardFormat(Map<String, Object> dbRecord) {
        Map<String, Object> result = new HashMap<>();
        Map<String,Object> stringObjectMap=userInfoMapper.getUserAsMap((String) dbRecord.get("user_id"));
        // 必填字段
        result.put("id", dbRecord.get("user_id"));

        result.put("name", Optional.ofNullable(dbRecord.get("name")).orElse("默认"));

        //dbRecord.put("avatar_path",s)

        // 带默认值的字段
        result.put("avatar",
                Optional.ofNullable(stringObjectMap.get("avatar_path"))
                        .orElse("/avatars/default.png"));

        result.put("roleType",
                Optional.ofNullable(stringObjectMap.get("auth"))
                        .map(auth -> {
                            // 数字或字符串类型兼容处理
                            String authStr = String.valueOf(auth).trim();
                            switch (authStr) {
                                case "1": return 1; // 学生
                                case "2": return 2; // 辅导员
                                case "3": return 3; // 咨询师
                                default:  return 1;  // 默认学生
                            }
                        })
                        .orElse(1) // 空值默认设为学生
        );

        return result;
    }
}
